package org.hyh.core.security.componet;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.hyh.core.Exception.TokenAuthenticationException;
import org.hyh.core.model.entity.SysUser;
import org.hyh.core.model.vo.LoginVo;
import org.hyh.core.service.UserService;
import org.hyh.core.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @auther :hyh
 * @desc :
 * @date :2020/7/13
 */
      //  该方法在DaoAuthenticationProvider#retrieveUser()被调用，也可以直接重写 provider中retrieveUser的方法。
@Service
@Slf4j
public class UserDetailsServiceImpl  implements UserDetailsService {

   @Autowired
   UserService userService;
   @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginVo loginVo = JSON.parseObject(username, LoginVo.class);
        if (!"123".equals(loginVo.getCode())) {
            throw new TokenAuthenticationException("验证码错误！");
        }
//        SysUser user = userService.getUserByUsernamePassword(loginVo.getUsername(), loginVo.getPassword());
        SysUser user = null;
        if (loginVo.getUsername().equals("hyh") &&  loginVo.getPassword().equals("123")) {
            user = new SysUser().setId("123").setUsername("hyh").setPassword(bCryptPasswordEncoder.encode("123"));

        }
        if (user == null) {
             throw new UsernameNotFoundException("账户名或密码错误！");
        }

        user.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_train_user", "ROLE_train_admin"));


        return user;
    }
}
